package com.fengye.modules.bo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.fengye.modules.domain.SysDictModule;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Data
@EqualsAndHashCode(callSuper = true)
public class SysDictTree extends SysDictModule implements Serializable {

    private List<SysDictTree> children = new ArrayList<>();

    public static List<SysDictTree> convert(List<SysDictModule> modules) {
        return modules.stream().map(module -> BeanUtil.copyProperties(module, SysDictTree.class)).collect(Collectors.toList());
    }


    public static List<SysDictTree> build(List<SysDictTree> nodeList) {
        if (CollUtil.isEmpty(nodeList)) {
            return null;
        }
        boolean flag = false;
        List<SysDictTree> treeNodes = new ArrayList<>(nodeList);
        List<SysDictTree> names = new ArrayList<>(nodeList);
        Iterator<SysDictTree> iterator = treeNodes.iterator();
        while (iterator.hasNext()) {
            SysDictTree node = iterator.next();
            List<SysDictTree> children = names.stream().filter(n ->
                            !n.getValue().equals(node.getValue())
                                    && n.getValue().startsWith(node.getValue()))
                    .collect(Collectors.toList());
            if (!CollUtil.isEmpty(children)) {
                names.removeAll(children);
                node.children = children;
                flag = true;
            }
        }

        List<String> values = names.stream().map(SysDictModule::getValue).toList();

        List<SysDictTree> result = treeNodes.stream().filter(treeNode -> values.contains(treeNode.getValue())).collect(Collectors.toList());

        result.forEach(node -> {
            node.children = build(node.getChildren());
        });
        return result;
    }


}
